package com.biscuit.page.basicservice.utils;

import java.util.concurrent.*;

/**
 * @author biscuit
 * @createTime 2024/6/17 14:32
 */
public class ExecutorUtil {

    private static final ExecutorService EXECUTOR;

    // 核心线程数
    private static final int CORE_POOL_SIZE = 7;

    // 最大线程数
    private static final int MAX_POOL_SIZE = 21;

    // 空闲线程最大等待时间
    private static final long KEEP_ALIVE_TIME = 60L;

    // 空闲线程最大等待时间的单位
    private static final TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;

    // 任务等待线程执行时，存储任务的队列
    private static final BlockingQueue<Runnable> EXECUTOR_WORK_QUEUE = new LinkedBlockingQueue<>();

    // 创建新线程时使用的线程创建工厂
    private static final ThreadFactory EXECUTOR_THREAD_FACTORY = Executors.defaultThreadFactory();

    // 等待被执行的任务超出存储队列时的任务拒绝策略
    private static final RejectedExecutionHandler EXECUTOR_HANDLER = new ThreadPoolExecutor.AbortPolicy();

    static {
        EXECUTOR = new ThreadPoolExecutor(
                CORE_POOL_SIZE,
                MAX_POOL_SIZE,
                KEEP_ALIVE_TIME,
                KEEP_ALIVE_TIME_UNIT,
                EXECUTOR_WORK_QUEUE,
                EXECUTOR_THREAD_FACTORY,
                EXECUTOR_HANDLER
        );
    }

    public static ExecutorService getThreadPool() {
        return EXECUTOR;
    }

}
